<template>
  <div>
    <el-dialog
      title="私人聊天室"
      :visible="privateChatRoomVisible"
      width="50%"
      center
      append-to-body
      :modal="false"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-container>
        <!-- 侧边信息 -->
        <el-aside class="chat-room-left" scroll="none">
          <!-- 用户操作框 -->
          <div class="user-operation-box">
            <!-- 头像 -->
            <div class="avatar-box">
              <span>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="头像"
                  placement="left-start"
                >
                  <img :src="userInfo.loginUrlAvatar" alt="" />
                </el-tooltip>
              </span>
            </div>
            <!-- 聊天信息，==> 加载组件后显示当前登录用户的好友信息以及聊天信息 -->
            <div class="message-box" @click="showChatMessage">
              <el-tooltip
                class="item"
                effect="dark"
                content="聊天信息"
                placement="left"
              >
                <i class="el-icon-chat-round"></i>
              </el-tooltip>
            </div>
            <!-- 搜索用户框 ==> 进行添加好友 -->
            <div class="search-user-box" @click="showSearchUser">
              <el-tooltip
                class="item"
                effect="dark"
                content="添加好友"
                placement="left-start"
              >
                <i class="el-icon-plus"></i>
              </el-tooltip>
            </div>
            <!-- 关闭按钮 -->
            <div class="close-chat-room" @click="closeChatRoomWindow">
              <el-tooltip
                class="item"
                effect="dark"
                content="关闭聊天室"
                placement="left-start"
              >
                <i class="el-icon-close"></i>
              </el-tooltip>
            </div>
          </div>
        </el-aside>

        <el-aside class="chat-room-middle">
          <searchUser v-if="searchUser" @clickUser="clickUser"></searchUser>
          <chatMessage
            v-if="chatMessage"
            @clickFriend="clickFriend"
            :cardNotice="cardNotice"
            :mySendMsg="mySendMsg"
          ></chatMessage>
        </el-aside>
        <el-container v-if="!searchUser">
          <!-- 聊天内容 -->
          <el-main class="chat-main" ref="chatMain">
            <div class="chat-content">
              <ul id="chatContent">
                <!-- 判断是否是自己发的还是别人发的, 根据id 和 leftOrRight  0 自己 1 对方 -->
                <li
                  :class="
                    message.userId === userInfo.uid
                      ? 'my-message'
                      : 'other-message'
                  "
                  v-for="(message, index) in sendAndAcceptMessage"
                  :key="index"
                  ref="messageRef"
                >
                  <div class="user-avatar" v-if="message.avatar">
                    <img :src="message.avatar" alt="" />
                  </div>
                  <div class="send-user-info">
                    <div class="username">
                      <span>{{ message.username }}</span>
                      <div
                        class="message-content"
                        :class="
                          message.userId === userInfo.uid
                            ? 'my-label'
                            : 'other-label'
                        "
                      >
                        <span>{{ message.message }}</span>
                      </div>
                    </div>
                  </div>
                  <div class="onOrOff" v-if="message.onOrOff === 1">
                    {{ message.username }}加入了基佬团
                  </div>
                  <div class="onOrOff" v-if="message.onOrOff === 0">
                    {{ message.username }}因受不了基佬团而光速退伍
                  </div>
                </li>
                <div
                  class="newMessage"
                  @click="redirectNewMessage"
                  v-if="getNewMessage"
                >
                  <span class="prompt">您有一条新的消息</span>
                  <span
                    class="close-prompt"
                    @click="getNewMessage = !getNewMessage"
                    >x</span
                  >
                </div>
              </ul>
            </div>
          </el-main>
          <!-- 输入框 -->
          <el-footer>
            <div class="char-sendMessage-input">
              <el-input
                v-model="message"
                placeholder="请在这里输入你要发送的内容哦!回车发送内容~~"
                @keyup.enter.native="sendMessage"
              ></el-input>
              <div style="text-align: right">
                <el-button size="mini" @click="sendMessage">发送</el-button>
              </div>
            </div>
          </el-footer>
        </el-container>
        <el-container v-if="searchUser">
          <!-- 聊天内容 -->
          <el-main class="chat-main">
            <div class="chat-content">
              <!-- 用户内容 -->
              <div class="user-msg-show" v-if="showMsg">
                <!-- 头像 -->
                <div class="avatar">
                  <img :src="clickUserInfo.avatar" alt="" />
                </div>
                <div class="user-msg">
                  <!-- 用户名 -->
                  <span class="username">
                    {{ clickUserInfo.username }}
                  </span>
                  <!-- 关注/粉丝 -->
                  <div class="follow-box">
                    <!-- 关注 -->
                    <span class="follower"
                      >粉丝: {{ clickUserInfo.followerCount }} /
                    </span>
                    <!-- 粉丝 -->
                    <span class="follow"
                      >关注: {{ clickUserInfo.followCount }}</span
                    >
                  </div>
                </div>
                <!-- 添加好友按钮 -->
                <el-button
                  type="success"
                  plain
                  style="margin-top: 20px"
                  @click="addFriend"
                  >添加好友</el-button
                >
              </div>
            </div>
          </el-main>
        </el-container>
      </el-container>
    </el-dialog>
  </div>
</template>

<script>
import searchUser from "./children/searchUser.vue";
import chatMessage from "./children/chatMessage.vue";
import UserApiRequest from "@/api/UserApiRequest";
const userApiRequest = new UserApiRequest();
export default {
  props: {
    privateChatRoomVisible: {
      default: false,
      typeof: Boolean,
    },
    privateChatRoom: {
      default: false,
    },
  },
  components: { searchUser, chatMessage },
  data() {
    return {
      userInfo: {},
      message: "",
      toUser: "",
      searchUser: false,
      chatMessage: true,
      getNewMessage: false,
      showMsg: false,
      sendAndAcceptMessage: [],
      cardNotice: {},
      mySendMsg: {},
      clickUserInfo: {},
    };
  },
  methods: {
    closeChatRoomWindow() {
      this.$emit("closeChatRoom", false);
    },
    showSearchUser() {
      this.searchUser = true;
      this.chatMessage = false;
    },
    showChatMessage() {
      this.searchUser = false;
      this.chatMessage = true;
    },
    // 点击的好友 ==> 进行聊天
    clickFriend(data) {
      this.sendAndAcceptMessage = [];
      this.toUser = data;
      // 获取聊天记录
      let entity = {
        loginUserId: this.userInfo.uid,
        friendUserId: this.toUser.friendUserId,
      };
      userApiRequest.getChattingRecords(entity).then((res) => {
        this.sendAndAcceptMessage = res.data.recordsVoList;
        this.autoScroll();
      });
    },
    // 点击用户 ==> 添加好友
    clickUser(id) {
      //点击卡片获取用户信息
      let data = {
        userId: id,
      };
      userApiRequest.getUserBlogInfo(data).then((res) => {
        this.clickUserInfo = res.data;
        this.showMsg = true;
      });
    },
    // 跳转新消息
    redirectNewMessage() {
      this.getNewMessage = !this.getNewMessage;
      this.$nextTick(() => {
        const lastMessage =
          this.$refs.messageRef[this.$refs.messageRef.length - 1];
        lastMessage.scrollIntoView({ behavior: "smooth" });
      });
    },
    autoScroll() {
      this.$nextTick(() => {
        const dom = this.$refs.chatMain.$el;
        dom.scrollTo({ top: dom.scrollHeight, behavior: "instant" });
      });
    },
    sendMessage() {
      if (this.message.trim("").length === 0) {
        this.$message.warning("你还没有输入内容哦");
        return;
      }
      if (!this.toUser) {
        this.$message.warning("请选择聊天对象");
        return;
      }

      let sendMessageInfo = {
        message: this.message,
        avatar: this.userInfo.loginUrlAvatar,
        username: this.userInfo.nickname,
        leftOrRight: "0",
        toUserId: this.toUser.toUserId,
        userId: this.userInfo.uid,
      };
      let data = {
        fromUserId: this.toUser.friendAddedUserId,
        toUserId: this.toUser.friendUserId,
        toUserAvatarUrl: this.userInfo.loginUrlAvatar,
        nickname: this.userInfo.nickname,
        message: this.message,
        type: "1",
      };
      this.sendAndAcceptMessage.push(sendMessageInfo);
      // 发送消息 给父组件进行发送
      this.$emit("sendPrivateMsg", data);
      this.autoScroll();
      this.mySendMsg = {
        message: this.message,
        toUserId: this.toUser.friendUserId,
      };
      this.message = "";
    },
    // 添加好友按钮
    addFriend() {
      this.$confirm("无需确认既可以添加好友", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            sendAddUserId: this.userInfo.uid,
            addUserId: this.clickUserInfo.userId,
          };
          userApiRequest.addFriend(data).then((res) => {
            if (res.code === 0) {
              this.$message.success(res.msg);
            } else if (res.code === -4007) {
              this.$message.warning(res.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消添加",
          });
        });
    },
  },
  mounted() {
    if (this.$store.state.isLogin) {
      this.userInfo = this.$store.state.userInfo;
    }
  },
  watch: {
    privateChatRoom: {
      handler(newVal) {
        const chatRoom = JSON.parse(newVal.data).chatRoom;
        if (chatRoom.userId === this.toUser.friendUserId) {
          this.sendAndAcceptMessage.push(chatRoom);
          if (JSON.parse(newVal.data).isNewMsg) {
            this.getNewMessage = true;
          }
        } else {
          this.cardNotice = chatRoom;
        }
      },
      deep: true,
    },
  },
};
</script>

<style lang="scss" scoped>
img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
.user-message {
  background-color: #c4c9d1;
}

.chat-main {
  overflow-y: scroll;
  overflow-x: none;
  height: 300px;
  background-color: #f6f6f6;
  .other-message {
    margin-top: 10px;
    display: flex;

    .user-avatar {
      margin-top: 10px;
    }
    .send-user-info {
      margin-left: 10px;
    }
    .message-content {
      flex-wrap: wrap;
      margin-top: 5px;
      padding: 8px;
      border: 1px solid #c4c9d1;
      background-color: #fff;
    }
    .other-label {
      position: relative;
      background-color: inherit;
      font-size: 12px;
      border-radius: 4px;
    }
    .other-label:before {
      position: absolute;
      content: "";
      top: 7px;
      left: -5px;
      width: 0.6666em;
      height: 0.6666em;
      border-style: inherit;
      border-color: inherit;
      border-width: 0 0 1px 1px;
      transform: rotate(45deg);
      background-color: #f6f6f6;
      background-image: none;
      z-index: 2;
      transition: background 0.1s ease;
    }
  }
  .my-message {
    position: relative;
    display: flex;
    justify-content: flex-end;
    padding-right: 40px;
    margin-top: 10px;

    .user-avatar {
      position: absolute;
      top: 0;
      right: 0;
      margin-top: 10px;
    }
    .send-user-info {
      margin-right: 20px;
      .username {
        text-align: right;
      }
    }
    .message-content {
      flex-wrap: wrap;
      margin-top: 5px;
      padding: 8px;
      border: 1px solid #c4c9d1;
      background-color: #9eea6a !important;
    }
    .my-label {
      position: relative;
      background-color: inherit;
      font-size: 12px;
      border-radius: 4px;
    }
    .my-label:before {
      position: absolute;
      content: "";
      top: 7px;
      right: -5px;
      width: 0.6666em;
      height: 0.6666em;
      border-style: inherit;
      border-color: inherit;
      border-width: 1px 1px 0px 0px;
      transform: rotate(45deg);
      background-color: #9eea6a;
      background-image: none;
      z-index: 2;
      transition: background 0.1s ease;
    }
  }
  .newMessage {
    position: absolute;
    bottom: 36%;
    right: 4%;
    padding: 10px 0;
    background-color: #fff;
    cursor: pointer;
    user-select: none;
    z-index: 9999;
    .prompt {
      display: inline-block;
      color: #37c735;
      padding: 0 10px;
      border-right: 1px solid #d1d2d3 !important;
    }
    .close-prompt {
      padding: 0 10px;
    }
  }
}
.chat-room-left {
  overflow-x: hidden;
  width: 50px !important;
  .user-operation-box {
    width: 50px;
    height: 100%;
    padding: 10px 0 0 0;
    background-color: #474574;
    .message-box {
      text-align: center;
      margin-top: 20px;
      color: #fff;
      cursor: pointer;
    }

    .avatar-box {
      text-align: center;
    }

    .search-user-box {
      margin-top: 20px;
      padding: 5px;
      color: #fff;
      text-align: center;
      cursor: pointer;
    }
    .close-chat-room {
      color: #fff;
      margin-top: 20px;
      text-align: center;
      cursor: pointer;
    }
  }
}

.chat-room-left::-webkit-scrollbar {
  display: none;
}
.chat-room-middle {
  display: flex;
  height: 500px;
  flex-direction: column;
  width: 200px !important;

  .user-card {
    padding: 14px;
    cursor: pointer;
    .content {
      .user-avatar {
        width: 50px;
        height: 50px;
        border-radius: 10%;
        float: right;
      }
      .username {
        font-weight: 700;
        margin: 10% 0;
        font-size: 16px;
      }
      .send-time {
        font-size: 1em;
        color: rgba(0, 0, 0, 0.4);
      }
      .last-message {
        font-size: 12px;
        margin-top: 4%;
      }
    }
  }
}
.chat-room-middle::-webkit-scrollbar {
  width: 0;
}
.chat-main::-webkit-scrollbar {
  display: none;
}

::v-deep .el-input__inner {
  border: none;
}

::v-deep .el-card__body {
  padding: 0;
}
.onOrOff {
  margin-left: 40%;
  font-size: 12px;
  text-align: center;
  color: #909294;
}
.chat-room-header-title {
  text-align: center;
  margin-bottom: 10px;
  color: red;
}
.user-msg-show {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .avatar img {
    width: 80px;
    height: 80px;
    border-radius: 50%;
  }
  .user-msg {
    text-align: center;
    margin-top: 15px;
    .username {
      font-weight: 700;
    }
    .follow-box {
      margin-top: 5px;
      font-size: 14px;
      color: #9a9ca1;
    }
  }
}
</style>
